package com.slz3.business.frame.api.wx;

import ch.qos.logback.core.joran.spi.XMLUtil;
import com.slz3.business.frame.api.tool.AppEnv;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.JDOMException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.Map;
import java.util.UUID;

/**
 * 验证是否是微信官网的信息
 * @author zhaozhongxin
 *
 */
public class WexinPayUtilApi {
	
	/*日志记录*/
	protected final static Log logger = LogFactory.getLog(WexinPayUtilApi.class);
	/*支付宝合作者身份ID*/
	private static final String MCH_ID= AppEnv.getInstance().getStringProp("weixin.mch_id", "1510207811");
	/*接口名称*/
	private static final String APPID=AppEnv.getInstance().getStringProp("weixin.appid", "wxe43cfe74061aaff1");;
	/*接口名称*/
	private static final String QUERY_URL=AppEnv.getInstance().getStringProp("weixin.queryurl", "https://api.mch.weixin.qq.com/pay/orderquery");;
	private static final String PAY_URL=AppEnv.getInstance().getStringProp("weixin.payurl", "https://api.mch.weixin.qq.com/pay/unifiedorder");;
	private static final String KEY=AppEnv.getInstance().getStringProp("weixin.key", "mishangkejiyouxiangongsi2018app2");;
	//private static final String NOTIFY_URL=AppEnv.getInstance().getStringProp("weixin.notify_url", "http://60.205.208.183:8081/appPay!appUserWechatPay.action");;
	//private static final String NOTIFY_URL=AppEnv.getInstance().getStringProp("weixin.notify_url", "http://www.mishangkeji.com:8081/appPay!appUserWechatPay.action");;
	private static final String NOTIFY_URL="http://60.205.208.183:8081/appPay!appUserWechatPay.action";
	//7e4bdb49.ngrok.io
//	private static final String OPENID=AppEnv.getInstance().getStringProp("weixin.openid", "");;
	private static final String SPBILL_CREATE_IP=AppEnv.getInstance().getStringProp("weixin.spbill_create_ip", "");;
	public static void main(String[] args) {
//		voilidata("20160131172127134");
//		voilidata("3830771459241966");
//		scanPay("20160418102844518","1");
		appScanPay("20160418102844518","1");
		System.out.println(UUID.randomUUID().toString().replace("-", ""));
	}
	@SuppressWarnings({ "unchecked", "deprecation" })
	public static String voilidata(String  orderno){
		String requestbody=createBodyXml(orderno);
		HttpClient client= new HttpClient();
		PostMethod postMethod = new PostMethod(QUERY_URL);//POST请求 微信查询路径
		postMethod.addRequestHeader("Content-Type", "application/xml;charset=UTF-8");
		postMethod.setRequestBody(requestbody);
		String responseXml="";
		try {
			client.executeMethod(postMethod);
			if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
				/**
				 * 返回来的报文
				 */
				responseXml =new String(postMethod.getResponseBody(),"utf-8") ;
			}
		} catch (IOException e) {
			logger.error("执行HTTP Post请求"+QUERY_URL+"时，发生异常！", e);
		} finally {
			postMethod.releaseConnection();
		}
		Map map=null;
		try {
			// TODO doXMLParse
//			map = XMLUtil.doXMLParse(responseXml);
		} catch (Exception e) {
			// TODO AppException
//			logger.error(AppException.getStackMsg(e));
		}
		
		String response_result="false";
		String   return_code = (String) map.get("return_code");
		String   result_code = (String) map.get("result_code");
		if("SUCCESS".equals(return_code.trim())&&"SUCCESS".equals(result_code.trim())){
			response_result="true";
			return response_result;
		}
		return response_result;
	}
	@SuppressWarnings({ "unchecked", "deprecation" })
	public static Map scanPay(String  orderno,String totalprice){
		String requestbody=createPayXml(orderno,totalprice);
		HttpClient client= new HttpClient();
		PostMethod postMethod = new PostMethod(PAY_URL);//POST请求 微信查询路径
		postMethod.addRequestHeader("Content-Type", "application/xml;charset=UTF-8");
		postMethod.setRequestBody(requestbody);
		String responseXml="";
		try {
			client.executeMethod(postMethod);
			if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
				/**
				 * 返回来的报文
				 */
				responseXml =new String(postMethod.getResponseBody(),"utf-8") ;
			}
		} catch (IOException e) {
			logger.error("执行HTTP Post请求"+QUERY_URL+"时，发生异常！", e);
		} finally {
			postMethod.releaseConnection();
		}
		Map map=null;
		try {
			// TODO doXMLParse
//			map = XMLUtil.doXMLParse(responseXml);
		} catch (Exception e) {
			// TODO AppException
//			logger.error(AppException.getStackMsg(e));
		}
		
		return map;
	}
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	public static Map appScanPay(String  orderno,String totalprice){
		String requestbody=createAppPayXml(orderno,totalprice);
		HttpClient client= new HttpClient();
		PostMethod postMethod = new PostMethod(PAY_URL);//POST请求 微信查询路径
		postMethod.addRequestHeader("Content-Type", "application/xml;charset=UTF-8");
		postMethod.setRequestBody(requestbody);
		String responseXml="";
		try {
			client.executeMethod(postMethod);
			if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
				/**
				 * 返回来的报文
				 */
				responseXml =new String(postMethod.getResponseBody(),"utf-8") ;
			}
		} catch (IOException e) {
			logger.error("执行HTTP Post请求"+QUERY_URL+"时，发生异常！", e);
		} finally {
			postMethod.releaseConnection();
		}
		Map map=null;
		try {
			// TODO doXMLParse
//			map = XMLUtil.doXMLParse(responseXml);
		} catch (Exception e) {
			// TODO AppException
//			logger.error(AppException.getStackMsg(e));
		}
		
		return map;
	}
//	private static String createBodyXml(String orderno) {
//		String nonceStr=UUID.randomUUID().toString().replace("-", "");
//		String origin="appid=wx7de939075177dacb"
//		            +"&mch_id=1316167301"
//		            +"&nonce_str="+nonceStr
//		            +"&out_trade_no="+orderno
//		            +"&key=mnbvcxzlkjhgfdsapoiuytrewq695235";
//		//String sign=MD5Encode(origin, null).toUpperCase();
//		String sign=getMessageDigest(origin.getBytes()).toUpperCase();
//		StringBuilder sbBuilder = new StringBuilder();
//		sbBuilder.append("<xml>");
//		sbBuilder.append("<appid>wx7de939075177dacb</appid>");
//		sbBuilder.append("<mch_id>1316167301</mch_id>");
//		sbBuilder.append("<nonce_str>"+nonceStr+"</nonce_str>");
//		sbBuilder.append("<out_trade_no>"+orderno+"</out_trade_no>");
//		sbBuilder.append("<sign>"+sign+"</sign>");
//		sbBuilder.append("</xml>");
//		return sbBuilder.toString();
//	}
	public static String createBodyXml(String orderno) {
		String nonceStr=UUID.randomUUID().toString().replace("-", "");
		String origin="appid="+APPID+"&mch_id="+MCH_ID+"&nonce_str="+nonceStr+"&out_trade_no="+orderno+"&key="+KEY;
		//String sign=MD5Encode(origin, null).toUpperCase();
		String sign=getMessageDigest(origin.getBytes()).toUpperCase();
		StringBuilder sbBuilder = new StringBuilder();
		sbBuilder.append("<xml>");
		sbBuilder.append("<appid>"+APPID+"</appid>");
		sbBuilder.append("<mch_id>"+MCH_ID+"</mch_id>");
		sbBuilder.append("<nonce_str>"+nonceStr+"</nonce_str>");
		sbBuilder.append("<out_trade_no>"+orderno+"</out_trade_no>");
		sbBuilder.append("<sign>"+sign+"</sign>");
		sbBuilder.append("</xml>");
		return sbBuilder.toString();
	}
	private static String createPayXml(String orderno,String totalprice) {
		String nonceStr="d4b6b4846cae4d4487668fa0c2e6349d";
//		String nonceStr=UUID.randomUUID().toString().replace("-", "");
		String origin="appid=wx7de939075177dacb"
					+"&body=\u4F1A\u5458\u5361"
					+"&device_info=WEB"
					+"&mch_id=1316167301"
					+"&nonce_str="+nonceStr
					+"&notify_url="+NOTIFY_URL
//					+"&openid=o2udmv4Cd51Ey8bbXwMLYk6P7hoE"
					+"&out_trade_no="+orderno
					+"&product_id=62235413214070356458058"
//					+"&spbill_create_ip="+SPBILL_CREATE_IP
					+"&total_fee="+totalprice
					+"&trade_type=NATIVE"
					+"&key=mnbvcxzlkjhgfdsapoiuytrewq695235";
		//String sign=MD5Encode(origin, null).toUpperCase();
		String sign=getMessageDigest(origin.getBytes()).toUpperCase();
		StringBuilder sbBuilder = new StringBuilder();
		sbBuilder.append("<xml>");
		sbBuilder.append("<appid>wx7de939075177dacb</appid>");
		sbBuilder.append("<body>"+"\u4F1A\u5458\u5361"+"</body>");//商品描述
		sbBuilder.append("<device_info>WEB</device_info>");//设备号
		sbBuilder.append("<mch_id>1316167301</mch_id>");
		sbBuilder.append("<nonce_str>"+nonceStr+"</nonce_str>");//随机字符串
		sbBuilder.append("<notify_url>"+NOTIFY_URL+"</notify_url>");
//		sbBuilder.append("<openid>o2udmv4Cd51Ey8bbXwMLYk6P7hoE</openid>");
		sbBuilder.append("<out_trade_no>"+orderno+"</out_trade_no>");//商户订单号
		sbBuilder.append("<product_id>62235413214070356458058</product_id>");//商户订单号
//		sbBuilder.append("<spbill_create_ip>"+SPBILL_CREATE_IP+"</spbill_create_ip>");//商户订单号
		sbBuilder.append("<total_fee>"+totalprice+"</total_fee>");
		sbBuilder.append("<trade_type>NATIVE</trade_type>");
		sbBuilder.append("<sign>"+sign+"</sign>");
		sbBuilder.append("</xml>");
		return sbBuilder.toString();
	}
	
	private static String createAppPayXml(String orderno,String totalprice) {
		String nonceStr="d4b6b4846cae4d4487668fa0c2e6349d";
//		String nonceStr=UUID.randomUUID().toString().replace("-", "");
		String origin="appid=wxe43cfe74061aaff1"
					+"&body=\u4F1A\u5458\u5361"
					+"&mch_id=1510891941"
					+"&nonce_str="+nonceStr
					+"&notify_url="+NOTIFY_URL
					+"&out_trade_no="+orderno
					+"&spbill_create_ip="+SPBILL_CREATE_IP
					+"&total_fee="+totalprice
					+"&trade_type=APP"
					+"&key=mishangkejiyouxiangongsi2018app2";
		String sign=getMessageDigest(origin.getBytes()).toUpperCase();
		StringBuilder sbBuilder = new StringBuilder();
		sbBuilder.append("<xml>");
		sbBuilder.append("<appid>wxe43cfe74061aaff1</appid>");
		sbBuilder.append("<body>"+"\u4F1A\u5458\u5361"+"</body>");//商品描述
		sbBuilder.append("<mch_id>1510891941</mch_id>");
		sbBuilder.append("<nonce_str>"+nonceStr+"</nonce_str>");//随机字符串
		sbBuilder.append("<notify_url>"+NOTIFY_URL+"</notify_url>");
		sbBuilder.append("<out_trade_no>"+orderno+"</out_trade_no>");//商户订单号
		sbBuilder.append("<spbill_create_ip>"+SPBILL_CREATE_IP+"</spbill_create_ip>");//商户订单号
		sbBuilder.append("<total_fee>"+totalprice+"</total_fee>");
		sbBuilder.append("<trade_type>APP</trade_type>");
		sbBuilder.append("<sign>"+sign+"</sign>");
		sbBuilder.append("</xml>");
		return sbBuilder.toString();
	}
	

	
	
	public final static String getMessageDigest(byte[] buffer) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(buffer);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

//	/**
//     * TODO 流的方式实现生成二TODO维码
//     */
//    public static void QRCodeEncoder(OutputStream OS,String imgFormat,String imgShowData,int imgSize) throws Exception {
//
//        Qrcode qrcode=new Qrcode();
//        qrcode.setQrcodeErrorCorrect('M');
//        qrcode.setQrcodeEncodeMode('B');
//        qrcode.setQrcodeVersion(7);
//        StringBuffer sb = new StringBuffer(imgShowData);
//        String result =sb.toString();
//        byte [] bt = result.getBytes("utf-8");
//        BufferedImage bi = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
//        Graphics2D gh2D = bi.createGraphics();
//        gh2D.setBackground(Color.WHITE);
//        gh2D.clearRect(0, 0, imgSize, imgSize);
//        gh2D.setColor(Color.BLACK);
//        if (bt.length>0){
//            boolean[][] s = qrcode.calQrcode(bt);
//            for (int i = 0; i < s.length; i++) {
//                for (int j = 0; j < s.length; j++) {
//                    if (s[j][i]) {
//                        gh2D.fillRect(j * 3 + 2, i * 3 + 2, 3, 3);
//                    }
//                }
//            }
//        }
//        gh2D.dispose();
//        bi.flush();
//        ImageIO.write(bi, imgFormat, OS);
//
//        System.out.println("doned!");
//    }

}
